package com.palmar.proxy.handler.socks;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.socksx.v5.DefaultSocks5InitialRequest;
import io.netty.handler.codec.socksx.v5.DefaultSocks5InitialResponse;
import io.netty.handler.codec.socksx.v5.Socks5AuthMethod;
import io.netty.handler.codec.socksx.v5.Socks5InitialResponse;

public class SocksAuthSelectorHandler extends SimpleChannelInboundHandler<DefaultSocks5InitialRequest> {
    @Override
    protected void messageReceived(ChannelHandlerContext ctx, DefaultSocks5InitialRequest msg) throws Exception {
        //是否包含用户名密码认证
        boolean accept = msg.authMethods().contains(Socks5AuthMethod.PASSWORD);
        //构建响应信息
        Socks5InitialResponse response = new DefaultSocks5InitialResponse(accept ? Socks5AuthMethod.PASSWORD :
                Socks5AuthMethod.UNACCEPTED);
        ChannelFuture channelFuture = ctx.channel().writeAndFlush(response);
        if (!accept) {
            //如果拒绝代理 响应完成后关闭连接
            channelFuture.addListener(ChannelFutureListener.CLOSE);
        }
    }
}
